from appserver import db_store
from sqlalchemy.sql import func
from sqlalchemy.sql import functions

"""
物联网网关
"""


class Gateway(db_store.Model):
    __tablename__ = "iot_gateway"
    # 这个键会在模型 声明时使用来把一个模型关联到一个特定引擎。
    # 如果没有为模型指定 bind key ，会默认连接（即 SQLALCHEMY_DATABASE_URI 配置的值）
    # 当你声明模型时，用 __bind_key__ 属性指定 bind:模型会自行连 接到指定的数据库连接
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64), unique=True, nullable=False, comment=u"网关名称")
    code = db_store.Column(db_store.String(64), unique=True, nullable=False, comment="网关编码")
    type = db_store.Column(db_store.Integer, default=0, comment=u"网关类型")
    icon = db_store.Column(db_store.String(255), comment="图标")
    username = db_store.Column(db_store.String(100), comment=u"访问用户名")
    password = db_store.Column(db_store.String(100), comment=u"访问密码")
    salt = db_store.Column(db_store.String(20), comment=u"安全码")
    clientid = db_store.Column(db_store.String(64), comment=u"客户端授权Key")
    description = db_store.Column(db_store.String(255), comment=u"分组描述")
    dis_order = db_store.Column(db_store.Integer, default=0, comment=u"排序")
    created = db_store.Column(db_store.DateTime, comment=u"创建时间")
    is_superuser = db_store.Column(db_store.Boolean, default=False, comment=u"超级用户")
    status = db_store.Column(db_store.Boolean, default=True, comment=u"状态")

    def __repr__(self):
        return "<Gateway: %s-%s" % (self.id, self.name)

    def get_max_id(self):
        val = db_store.session.query(func.max(Gateway.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):
        try:
            if self.id == None or self.id == 0:
                self.id = self.get_max_id() + 1
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False
